package com.jwx.mycar.service.impl;


import com.jwx.mycar.entity.po.Picture;
import com.jwx.mycar.entity.po.Recognition;
import com.jwx.mycar.entity.po.Stat;
import com.jwx.mycar.mapper.PictureMapper;
import com.jwx.mycar.mapper.StatMapper;
import com.jwx.mycar.service.PictureService;
import com.jwx.mycar.utils.AIImage;
import com.jwx.mycar.utils.GetPicFromUrl;
import com.jwx.mycar.utils.KeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import org.springframework.stereotype.Service;

import java.util.List;

import static com.jwx.mycar.common.Constants.TMP_FILE;

@Service("pictureService")
public class PictureServiceImpl implements PictureService {
	@Autowired
	private PictureMapper pictureMapper;
	
	@Autowired
	private StatMapper statMapper;
	
	@Override
	public Picture save(Picture picture) {
		picture.setPicId(KeyUtil.genUniqueKey());
		boolean su= pictureMapper.save(picture);
		return picture;
	}
	@Override
	public List<Recognition> detectImage(String url) {
		GetPicFromUrl.saveToFile(url);//将网络图片储存为临时本地图片
		List<Recognition> list = AIImage.classifyByURL(TMP_FILE);//调用图片植物识别接口
		//GetPicFromUrl.deleteTmpFile();//删除临时图片文件
		return list;//返回图片识别信息
	}



//	@Override
//	public List<PicturePO> find(int pageNum, int pageSize, int userId) {
//		if (pageNum <= 1) pageNum = 1;
//		if (pageSize <= 0 || pageSize >= 20) pageSize = 20;
//		int offset = (pageNum - 1) * pageSize;
//
//		MapSqlParameterSource ps = new MapSqlParameterSource();
//		StringBuilder sb = new StringBuilder();
//		sb.append("select p.pic_id, p.pic_path, u.username, s.up_count, s.down_count from picture p");
//		sb.append(" inner join user u on p.user_id = u.user_id");
//		sb.append(" left join (select sum(s.up_count) as up_count, sum(s.down_count) as down_count, s.pic_id from stat s group by s.pic_id) s");
//		sb.append(" on p.pic_id = s.pic_id");
//		sb.append(" order by p.pic_id desc");
//		sb.append(" limit :offset, :pageSize");
//		ps.addValue("offset", offset);
//		ps.addValue("pageSize", pageSize);
//
//		final List<PicturePO> picList = new ArrayList<PicturePO>();
//		namedParameterJdbcTemplate.query(sb.toString(), ps, new RowCallbackHandler() {
//			public void processRow(ResultSet rs) throws SQLException {
//				PicturePO pic = new PicturePO();
//				pic.setPicId(rs.getInt("pic_id"));
//				pic.setPicPath(rs.getString("pic_path"));
//				pic.setUsername(rs.getString("username"));
//				pic.setUpCount(rs.getInt("up_count"));
//				pic.setDownCount(rs.getInt("down_count"));
//				picList.add(pic);
//			}
//		});
//
//		// 有登录用户，统计该用户是否点赞或者点踩了某张图片
//		if (userId > 0 && picList.size() > 0) {
//			List<Integer> ids = new ArrayList<Integer>();
//			for (int i = 0; i < picList.size(); i++) {
//				ids.add(picList.get(i).getPicId());
//			}
//			MapSqlParameterSource ps1 = new MapSqlParameterSource();
//			String sql = "select pic_id, up_count, down_count from stat s where s.user_id = :userId and s.pic_id in (:picIds)";
//			ps1.addValue("userId", userId);
//			ps1.addValue("picIds", ids);
//			namedParameterJdbcTemplate.query(sql, ps1, new RowCallbackHandler() {
//				@Override
//				public void processRow(ResultSet rs) throws SQLException {
//					int picId = rs.getInt("pic_id");
//					int upCount = rs.getInt("up_count");
//					int downCount = rs.getInt("down_count");
//					for (int i = 0; i < picList.size(); i++) {
//						if (picList.get(i).getPicId() == picId) {
//							picList.get(i).setUp(upCount > 0);
//							picList.get(i).setDown(downCount > 0);
//						}
//					}
//				}
//
//			});
//		}
//
//		return picList;
//	}
//
//	@Override
//	public int getCount() {
//		MapSqlParameterSource ps = new MapSqlParameterSource();
//		StringBuilder sb = new StringBuilder();
//		sb.append("select count(*) from picture p");
//		sb.append(" inner join user u on p.user_id = u.user_id");
//		sb.append(" left join (select sum(s.up_count) as up_count, sum(s.down_count) as down_count, s.pic_id from stat s group by s.pic_id) s");
//		sb.append(" on p.pic_id = s.pic_id");
//
//		return namedParameterJdbcTemplate.queryForObject(sb.toString(), ps, Integer.class);
//	}
//
	@Override
	public int upFile(String picId, String userId) {
		Integer count;
		try {
			count = statMapper.queryUpCountBypicIdAndUserId(picId,userId);
		} catch(EmptyResultDataAccessException e) {
			count = null;
		}
		// 没有记录，插入
		if (count == null) {
			count=1;
			Stat stat = new Stat();
			stat.setPicId(picId);
			stat.setUserId(userId);
			stat.setStateId(KeyUtil.genUniqueKey());
			statMapper.add(stat);
		} else {
			count += 1;
			statMapper.update(count,picId,userId);
		}
		// 获取总的点赞数
		count  = statMapper.getAllUpCount(picId);
		//String sql = "select sum(up_count) from stat where pic_id=? group by pic_id";


		return count;
	}

	@Override
	public int getPicCount(String userId) {
		int count = pictureMapper.getPicCount(userId);
		return count;
	}

	@Override
	public int getUpById(String picId) {
		return statMapper.getAllUpCount(picId);
	}

//
//	@Override
//	public int downFile(int picId, int userId) {
//		String selectSql = "select down_count from stat where pic_id=? and user_id=?";
//		Integer count;
//		try {
//			count = jdbcTemplate.queryForObject(selectSql, new Object[] {picId, userId}, Integer.class);
//		} catch(EmptyResultDataAccessException e) {
//			count = null;
//		}
//		// 没有记录，插入
//		if (count == null) {
//			count = 1;
//			String insertSql = "insert into stat(user_id, pic_id, down_count) values(?,?,?)";
//			jdbcTemplate.update(insertSql, new Object[] {userId, picId, count});
//		} else {
//			count += 1;
//			String updateSql = "update stat set down_count=? where pic_id=? and user_id=?";
//			jdbcTemplate.update(updateSql, new Object[] {count, picId, userId});
//		}
//		// 获取总的点赞数
//		String sql = "select sum(down_count) from stat where pic_id=? group by pic_id";
//		count = jdbcTemplate.queryForObject(sql, new Object[] {picId}, Integer.class);
//
//		return count;
//	}
//
//	@Override
//	public PicturePO findById(int picId, int userId) {
//		MapSqlParameterSource ps = new MapSqlParameterSource();
//		StringBuilder sb = new StringBuilder();
//		sb.append("select p.pic_id, p.pic_path, u.user_id, u.username, s.up_count, s.down_count from picture p");
//		sb.append(" inner join user u on p.user_id = u.user_id");
//		sb.append(" left join (select sum(s.up_count) as up_count, sum(s.down_count) as down_count, s.pic_id from stat s group by s.pic_id) s");
//		sb.append(" on p.pic_id = s.pic_id");
//		sb.append(" where p.pic_id = :picId");
//		ps.addValue("picId", picId);
//
//		PicturePO pp = new PicturePO();
//		try {
//			namedParameterJdbcTemplate.queryForObject(sb.toString(), ps, new RowMapper<PicturePO>() {
//				@Override
//				public PicturePO mapRow(ResultSet rs, int rowNum) throws SQLException {
//					pp.setPicId(picId);
//					pp.setUserId(rs.getInt("user_id"));
//					pp.setPicPath(rs.getString("pic_path"));
//					pp.setUsername(rs.getString("username"));
//					pp.setUpCount(rs.getInt("up_count"));
//					pp.setDownCount(rs.getInt("down_count"));
//					return pp;
//				}
//
//			});
//
//			// 获取当前用户的点赞数
//			if (userId > 0) {
//				MapSqlParameterSource ps1 = new MapSqlParameterSource();
//				String sql = "select pic_id, up_count, down_count from stat s where s.user_id = :userId and s.pic_id = :picId";
//				ps1.addValue("userId", userId);
//				ps1.addValue("picId", picId);
//				namedParameterJdbcTemplate.query(sql, ps1, new RowCallbackHandler() {
//					@Override
//					public void processRow(ResultSet rs) throws SQLException {
//						int upCount = rs.getInt("up_count");
//						int downCount = rs.getInt("down_count");
//						pp.setUp(upCount > 0);
//						pp.setDown(downCount > 0);
//					}
//
//				});
//			}
//		} catch(Exception e) {}
//		return pp;
//	}
//	@Override
//	public List<Recognition> detectImage(String url) {
//		GetPicFromUrl.saveToFile(url);//将网络图片储存为临时本地图片
//		List<Recognition> list = AIImage.classifyByURL(TMP_FILE);//调用图片植物识别接口
//		//GetPicFromUrl.deleteTmpFile();//删除临时图片文件
//		return list;//返回图片识别信息
//	}
}
